#include "comcommandparser.h"
#include "../common/comiocontroller.h"

QVector<ComCommandFormat>* ComCommandParser::m_scCommandInfo = NULL;

ComCommandParser::ComCommandParser(QObject *parent) :
    QObject(parent)
{
}

bool ComCommandParser::parseInput(QString* input, QStringList& parsedInput)
{
    if(m_scCommandInfo == NULL)
        return false;

    parsedInput = input->split(" ");
    if(parsedInput.size() == 0)
        return false;
    for(int i = 0; i < this->m_scCommandInfo->size(); i++) {
        //match the command
        if( (m_scCommandInfo->at(i).name == parsedInput[0])
                && (m_scCommandInfo->at(i).leastArgNum <= parsedInput.size()-1)
                && (m_scCommandInfo->at(i).mostArgNum >= parsedInput.size()-1) ) {
            //invoke the command
            const QMetaObject* metaObj= m_scCommandInfo->at(i).metaObject;
            QObject* obj = metaObj->newInstance();
            ComAbstractCommand* cmd = (ComAbstractCommand *)obj;
            if( cmd->execute(parsedInput) == false ) {
                ComIOController::getInstance()->msgOutput(QString("<ComCommandParser::parseInput>:")+metaObj->className()+QString(" Execution Failed!"), MSG_ERROR);
                return false;
            }else{
                return true;
            }
        }
    }
    ComIOController::getInstance()->msgOutput("<ComCommandParser::parseInput>:No matched command.");
    return false;
}


